package com.mayikt.commodity.controller;


import com.mayikt.base.BaseResponse;
import com.mayikt.commodity.feign.ProductDetailsFeign;
import com.mayikt.resp.dto.ProductDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import org.apache.commons.io.IOUtils;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


@Controller
public class CommodityIndexController {

    @Autowired
    private ProductDetailsFeign productDetailsFeign;

    @RequestMapping("/getProductsearchDetails")
    public String getProductsearchDetails(Long productId, HttpServletRequest request) {
        // 控制层采用feign客户端调用商品服务接口
        BaseResponse<ProductDto> productsearchDetails = productDetailsFeign.getProductsearchDetails(productId);
        ProductDto productDto = productsearchDetails.getData();
        request.setAttribute("p", productDto);
        return "productsearchDetails";
    }

    @RequestMapping("/generateHtml")
    @ResponseBody
    public String generateHtml(Long productId) throws IOException, TemplateException {
        //创建配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        //设置模板路径
        String classpath = this.getClass().getResource("/").getPath();
        configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
        //设置字符集
        //configuration.setDefaultEncoding("UTF‐8");
        //加载模板
        Template template = configuration.getTemplate("productsearchDetails.ftl");
        //数据模型
        Map<String, Object> map = new HashMap<>();
        // 调用商品服务接口获取商品详情的数据
        BaseResponse<ProductDto> productsearchDetails = productDetailsFeign.getProductsearchDetails(productId);
        ProductDto productDto = productsearchDetails.getData();
        map.put("p", productDto);
        //静态化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        InputStream inputStream = IOUtils.toInputStream(content);
        //输出文件  nginx 目录
        Integer id = productDto.getId();
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\devtool\\nginx\\nginx-1.17.3\\html\\" + id + ".html"));
        int copy = IOUtils.copy(inputStream, fileOutputStream);
        return copy > 0 ? "success" : "fail";
    }
}
